import logging
import logging.handlers
from pathlib import Path
import sys
from datetime import datetime

from PySide6.QtCore import QThread, Signal

class ApiLog(QThread):
    rel_tip_signal = Signal(str, str)

    def __init__(self):
        super().__init__()
        # 获取 .exe 的真实路径
        if getattr(sys, 'frozen', False):  # 判断是否在打包环境中
            exe_path = Path(sys.executable).resolve().parent
        else:
            exe_path = Path(__file__).resolve().parent.parent

        self.log_dir = exe_path / 'logs'

    def run(self):
        self.log_dir.mkdir(exist_ok=True)
        log_file = self.log_dir / f"{datetime.now().strftime('%Y%m%d')}.log"

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(source)s - %(message)s', datefmt='%H:%M:%S')

        info_handler = logging.handlers.TimedRotatingFileHandler(log_file, when='D', interval=1, backupCount=7, encoding='utf-8')
        info_handler.setLevel(logging.INFO)
        info_handler.setFormatter(formatter)

        self.logger.addHandler(info_handler)
    
    def add_log(self, source: str, message: str):
        adapter = logging.LoggerAdapter(self.logger, {'source': source})
        adapter.info(message)